$(document).ready(function(){
	getArticle();
});


function getArticle(){
	$('#tableid').DataTable({
        dom: '<"top">rt<"bottom"flip><"clear">',
        language: {
            "sUrl":'../static/plugins/datatables/language.json'
        },
        "searching": false,
        "processing": true,
        "serverSide": true,
        ajax:{
            url:'/article/get-article',
            type:'post',
            data:function(d){
            	d.article_title = $('#article_title').val();
            	d.category_id = $('#category_id').val();
            },
            error:getError,
        },
        aoColumns: [
            { "data": "", "bSortable": false},
            { "data": "id", "bSortable": true},
            { "data": "article_title", "bSortable": false },
            { "data": "id", "bSortable": false},
            { "data": "category_title", "bSortable": false },
            { "data": "sort", "bSortable": true },
            { "data": "use_flg", "bSortable":false },
            { "data": "is_release", "bSortable":false }
        ],
        columnDefs: [
            {
                "targets": [0],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                	var html = '<a href="javascript:" onclick="changeArticle('+ full.id +')">修改</a>';
                	if(full.article_link != ''){
                		html += '&nbsp;|&nbsp;<a href="'+full.article_link+'" target=_blank>查看</a>';
                	}else{
                		html += '&nbsp;|&nbsp;<a href="javascript:" onclick="articlePreview('+ full.id +','+ full.category_id +')">预览</a>';
                	}
                	return html;
                }
            },
            {
                "targets": [3],
                "orderable":false,
                "searchable":false,
                "render": function(data, type, full) {
                    return '<a href="javascript:" onclick="chooseSeo('+ full.id +',4)">修改</a>';
                }
            },
            {
            	"targets": [6],
                "data": "use_flg",
                "render": function(data, type, full) {
                	return html = '<span class="switch" data-id="'+ full.id +'" data-flg="'+(data == 1 ? 0 : 1)+'"><input  style="width:20px;height:20px;" type="checkbox" '+(data == 1 ? 'checked="checked"' : '')+' class="input-check"></span>';
                }
            },
            {
                "targets": [7],
                "data": "is_release",
                "render": function(data, type, full) {
                	var html = '';
                	if(data == 0){
                		html += '<a href="javascript:" class="'+(data == 1 ? 'text-danger' : '')+'" onclick="changeArticleStatus('+ full.id +',1,2)">发布</a>';
                	}else{
                		html += '<span class="text-success">已发布</span>';
                	}
                    return html;
                }
            }
        ],
        order: [[ 5, "asc"]],
    });
}

function articlePreview(article_id,category_id){
	var params = 'id';
	var type = 1;
	if(category_id==6 || category_id==9){
		params = 'news_id';
		type = 2;
	}
	window.open('/article/preview?'+params+'='+article_id+'&type='+type);  
}

function table_list_reload(){
	var table = $('#tableid').DataTable();
    table.ajax.reload();
}

function changeArticleStatus(id,status,type){
	if(type == 2){
		title = '确定不发布此文章吗？';
		if(status == 1){
			title = '确定发布此文章吗？';
		}
	}else{
		title = '确定禁用此文章吗？';
		if(status == 1){
			title = '确定启用此文章吗？';
		}
	}
	$.jBox.confirm(title, "提示", function(v){
        if (v == 'ok'){
            $.post('/article/change-article-status',{id:id,status:status,type:type},success,'json');
            return false;
            function success(data){
                $.jBox.close();
                if(data.code == 200)
                {
                    $.jBox.tip('处理成功', 'success');
                    window.setTimeout(function () { table_list_reload(); }, 1000);
                }
                else{
                    $.jBox.error(data.val, '错误');
                }
            }
        }else{
            $.jBox.close();
            if(type == 1){
            	if(status == 1){
            		$('#tableid').find('span[data-id='+id+']').children('input').prop('checked',false);
            	}else{
            		$('#tableid').find('span[data-id='+id+']').children('input').prop('checked',true);
            	}
            }
        }
    });
}

function changeArticle(id){
	$.post('/article/get-article-detail',{id:id},success,'json');
	function success(data){
    	if(data.code == 200){
    		var result = data.val;
    		var id = $('#article-modal');
    		id.modal('show');
    		id.find('input[name=article_id]').val(result.id);
    		id.find('select[name=category_id]').val(result.category_id);
    		id.find('input[name=article_title]').val(result.article_title);
    		id.find('input[name=sort]').val(result.sort);
    		id.find('input[name=article_pic]').val(result.article_pic);
    		if(result.article_pic){
    			id.find('.show-img-btn').removeClass('hide');
    		}
    		id.find('input[name=article_link]').val(result.article_link);
    		id.find('select[name=use_flg]').val(result.use_flg);
    		id.find('select[name=article_classification]').val(result.article_classification);
    		//change by lizenan 20180416   【后台需求】文章列表增加标识和PC/Mobile视频链接的维护  585  start
    		id.find('select[name=article_identification]').val(result.article_identification);
    		id.find('input[name=video_url_pc]').val(result.video_url_pc);
    		id.find('input[name=video_url_wap]').val(result.video_url_wap);
    		//change by lizenan 20180416   【后台需求】文章列表增加标识和PC/Mobile视频链接的维护  585  end
    		id.find('#summary').val(result.summary);
    		var article_detail_pic = jQuery.parseJSON(result.article_detail_pic);
    		var html = '';
    		if(article_detail_pic != null && article_detail_pic != ''){
    			article_detail_pic.forEach(function(i){
        			html += '<tr>'+
        	        '<td><input name="article_detail_pic[]" value="'+i+'" class="form-control"></td>'+
        	        '<td><a href="javascript:;" class="up_input_table_tr">上移</a> | '+
        	        '<a href="javascript:;" class="down_input_table_tr">下移</a> | '+
        	        '<a class="del_input_table_tr" href="javascript:;">删除</a> | '+
        	        '<a class="update_pic" href="javascript:;">上传图片</a> | '+
        	        '<a class="select_pic" onclick="showImg($(this).parents(\'tr\').find(\'input\').val())" href="javascript:;">查看图片</a></td>'+
        	        '</tr>';;
        		});
    		}
    		$('#input_table').find('tbody').html(html);
    		id.find('textarea[name=content]').val(result.description);
        }else{
        	$.jBox.error(data.val, '错误');
        }
    }
}

function showImg(img_url){
	if(img_url == '' || img_url == null || img_url == undefined){
        $.jBox.error('数据为空', '错误');
        return false;
    }
	var json = {
        "title": "分类图片", //相册标题
        "id": 0, //相册id
        "start": 0, //初始显示的图片序号，默认0
        "data": [   //相册包含的图片，数组格式
            {
                "alt": "",//图片名
                "pid": 0, //图片id
                "src": $('#imageBathUrl').val() + img_url, //原图地址
                "thumb": "" //缩略图地址
            }
        ]
    };
    layer.photos({
        photos: json
    });
}

//重置操作
$('#reset_button').click(function(){
    $('#article_title').val('');
    $('#category_id').val('');
    table_list_reload();
});

$('.article-show-btn').on('click',function(){
	var id = $('#article-modal');
	id.modal('show');
	id.find('input[name=article_id]').val('');
	id.find('input[name=article_title]').val('');
	id.find('input[name=sort]').val('');
	id.find('input[name=article_pic]').val('');
	id.find('input[name=article_link]').val('');
	id.find('.show-img-btn').addClass('hide');
	id.find('select[name=use_flg]').val(1);
	id.find('select[name=article_classification]').val('');
	//change by lizenan 20180416   【后台需求】文章列表增加标识和PC/Mobile视频链接的维护  585  start
	id.find('select[name=article_identification]').val('');
	id.find('input[name=video_url_pc]').val('');
	id.find('input[name=video_url_wap]').val('');
	//change by lizenan 20180416   【后台需求】文章列表增加标识和PC/Mobile视频链接的维护  585  end
	id.find('textarea[name=content]').val('');
	id.find('#summary').val('');
	$('#input_table').find('tbody').html('');
	$('#content').xheditor();
});

$('#article-modal').on('click','.ajax_post_tag',function(){
	var form = $('#article_form');
	var article_title = form.find('input[name=article_title]').val();
    if(article_title == ''){
        $.jBox.error('请填写文章标题', '错误');
        return false;
    }
    var sort = $('#sort').val();
    if(sort == ''){
        $.jBox.error('请填写文章排序编号', '错误');
        return false;
    }
    var article_link = $('#article_link').val();
    var content = $('#content').val();
    if(content == '' && article_link == ''){
        $.jBox.error('外部链接或文章内容必须填写一项', '错误');
        return false;
    }
    $.post(form.attr('action'),form.serialize(),success,'json');
    return false;
	function success(data){
        if(data.code == 200)
        {
            $.jBox.tip('处理成功', 'success');
            window.setTimeout(function () {
                $('#article-modal').modal('hide');
                table_list_reload();
            }, 1000);
        }
        else{
            $.jBox.error(data.val, '错误');
        }
	}
});

//大图图片上传按钮事件
$('.upload-img-btn-main').click(function(){
	$('#img_type').val(1);
    $('.upload_file_ot').trigger('click');
});

$('.upload_file_ot').change(function(){
    if(this.value != ''){
    	$('#upload_form_update').submit();
    }
});

$('#upload_form_update').submit(function(e){
    e.preventDefault();
    $(this).ajaxSubmit({
        success:function(data){
            var result = $.parseJSON(data);
            if(result.code == 500){
                $.jBox.error(result.val, '错误');
            }else{
            	if(result.val){
            		var img_type = $('#img_type').val();
            		if(img_type == 1){
            			$('#article_pic').val(result.val);
                		$('.show-img-btn').removeClass('hide');
            		}else{
            			var len = $('#check_img_val').val();
            			var i=0;
            			$('.tbody-class').find('tr').each(function(){
                    		if(eval(len) == eval(i)){
                    			$(this).find('input[name="article_detail_pic[]"]').val(result.val);
                    		}
                        	i++;
                        });
            		}
            	}
            	$('input[type=file]').closest('form').get(0).reset();
            }
        }
    });
});

$("#content").xheditor({
	upImgUrl: '/common/xhedit-upload',
	upImgExt: "jpg,jpeg,gif,bmp,png",
	onUpload:insertUpload,
    height:600                                                      //设置编辑器的高度
},true);

function insertUpload(arrMsg)
{
	var i,msg;
	for(i=0;i<arrMsg.length;i++)
	{
		msg=arrMsg[i];
		$("#xheImgUrl").html(msg);
	}
}

$('#tableid').on('click','.input-check',function(){
	var id = $(this).parent().attr('data-id');
	var use_flg = $(this).parent().attr('data-flg');
	changeArticleStatus(id,use_flg,1);
});

$('#add_input').on('click',function(){
    var html = '<tr>'+
        '<td><input name="article_detail_pic[]" class="form-control"></td>'+
        '<td><a href="javascript:;" class="up_input_table_tr">上移</a> | '+
        '<a href="javascript:;" class="down_input_table_tr">下移</a> | '+
        '<a class="del_input_table_tr" href="javascript:;">删除</a> | '+
        '<a class="update_pic" href="javascript:;">上传图片</a> | '+
        '<a class="select_pic" onclick="showImg($(this).parents(\'tr\').find(\'input\').val())" href="javascript:;">查看图片</a></td>'+
        '</tr>';
    $('#input_table').find('tbody').append(html);
});

$('table').delegate('.del_input_table_tr','click',function(){
    $(this).parents('tr').remove();
});

$('table').delegate('.up_input_table_tr','click',function(){
    var tr_index = $(this).parents('tr').index();
    if(eval(tr_index) == 0){
        return true;
    }else{
        var obj = $(this).parents('tr').clone();
        $(this).parents('tr').prev().before(obj);
        $(this).parents('tr').remove();
    }
});

$('table').delegate('.down_input_table_tr','click',function(){
    var tr_index = $(this).parents('tr').next().index();
    if(eval(tr_index) > eval(-1)){
        var obj = $(this).parents('tr').clone();
        $(this).parents('tr').next().after(obj);
        $(this).parents('tr').remove();
    }
});

$('table').on('click','.update_pic',function(){
	var len = $(this).parents('tr').index();
	$('#check_img_val').val(len);
	$('#img_type').val(2);
    $('.upload_file_ot').trigger('click');
});